package com.lovezy.platform.wiki.service.impl;

import com.github.pagehelper.PageInfo;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.filestore.service.FileHelper;
import com.lovezy.platform.wiki.form.GameInfoForm;
import com.lovezy.platform.wiki.mapper.GameMapper;
import com.lovezy.platform.wiki.model.Game;
import com.lovezy.platform.wiki.query.WikiQuery;
import com.lovezy.platform.wiki.service.GameService;
import com.lovezy.platform.wiki.vo.WikiVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static com.lovezy.platform.wiki.form.GameInfoFormManager.toGame;
import static com.lovezy.platform.wiki.service.impl.GameRuleServiceImpl.ruleUrl;

/**
 * Created by jin on 2017/11/4.
 */
@Service
public class GameServiceImpl extends MapperService<Game,Integer,GameMapper> implements GameService{

    @Autowired
    private FileHelper fileHelper;

    @Override
    public PageInfo<WikiVo> selectList(WikiQuery query) {
        return Pager.doPageInfo(query, () -> {
            List<WikiVo> wikiVos = mapper.selectList(query);
            wikiVos.forEach(wikiVo -> {
                wikiVo.setLogo(fileHelper.toDownloadUrl(wikiVo.getLogo()));
                Map<String, String> ruleUrls = ruleUrl(wikiVo.getId());
                if (ruleUrls != null) {
                    wikiVo.setPdf(ruleUrls.get("pdf"));
                    wikiVo.setViewUrl(ruleUrls.get("viewUrl"));
                }
            });
        });
    }

    @Override
    public Game insertGame(GameInfoForm form) {
        Game game = toGame(form);
        mapper.insertSelective(game);
        return game;
    }

    @Override
    public void incrementHit(Integer gameId,Integer hitNum) {
        Game game = new Game();
        game.setId(gameId);
        game.setHit(hitNum);
        mapper.incrementHit(game);
    }

    @Override
    public Game selectById(@NotNull Integer gameId) {
        return mapper.selectByPrimaryKey(gameId);
    }

    @Override
    public void updateGame(@NotNull Game game) {
        mapper.updateByPrimaryKeySelective(game);
    }

    @Override
    public WikiVo findWikiById(@NotNull Integer gameId) {
        WikiQuery query = new WikiQuery();
        query.setGameId(gameId);
        return mapper.findWikiById(query);
    }
}
